﻿using CSLC.WeChat.PublicAccount;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;

namespace CSLC.WeChat.UI.MVC.Controllers
{
    public class WeixinInterfaceController : Controller
    {
        //
        // GET: /WeixinInterface/

        public ActionResult Index()
        {
            string result = string.Empty;
            if (Validate())
            {
                if (Request.HttpMethod == WebRequestMethods.Http.Get)
                    result = Request["echostr"];
                else if (Request.HttpMethod == WebRequestMethods.Http.Post)
                    result = HandlePost();
            }
            else
            {
                Message.Insert(new Message(MessageType.Exception, "校验消息失败。\r\n地址：" + Request.RawUrl));
                result = "校验消息失败。\r\n地址：" + Request.RawUrl;
            }
            return Content(result);
        }


        /// <summary>
        /// 验证消息的有效性
        /// </summary>
        /// <returns>如果消息有效，返回true；否则返回false。</returns>
        private bool Validate()
        {
            string username =string.IsNullOrEmpty( Request["username"])?ConfigurationManager.AppSettings["CSLCPublicUserName"]:Request["username"];  //在接口配置的URL中加入了username参数，表示哪个微信公众号
            AccountInfo account = AccountInfoCollection.GetAccountInfo(username);
            if (account == null)
                return false;
            string token = account.Token;
            string signature = Request["signature"];
            string timestamp = Request["timestamp"];
            string nonce = Request["nonce"];
            if (string.IsNullOrWhiteSpace(signature) || string.IsNullOrWhiteSpace(timestamp) || string.IsNullOrWhiteSpace(nonce))
                return false;
            return CSLC.WeChat.PublicAccount.Utility.CheckSignature(signature, token, timestamp, nonce);
        }
        /// <summary>
        /// 处理微信的POST请求
        /// </summary>
        /// <param name="context"></param>
        /// <returns>返回xml响应</returns>
        private string HandlePost()
        {
            RequestMessageHelper helper = new RequestMessageHelper(Request);
            if (helper.Message != null)
            {
                Message.Insert(new Message(MessageType.Request, helper.Message.ToString()));
                ResponseBaseMessage responseMessage = HandleRequestMessage(helper.Message);
                Message.Insert(new Message(MessageType.Response, responseMessage.ToString()));
                return responseMessage.ToXml(helper.EncryptType);
            }
            else
                return string.Empty;
        }

        /// <summary>
        /// 处理请求消息，返回响应消息
        /// </summary>
        /// <returns>返回响应消息</returns>
        private ResponseBaseMessage HandleRequestMessage(RequestBaseMessage requestMessage)
        {
            ResponseTextMessage response = new ResponseTextMessage(requestMessage.FromUserName, requestMessage.ToUserName,
                DateTime.Now, string.Format("自动回复，请求内容如下：\r\n{0}", requestMessage));
            response.Content += "\r\n<a href='http://wzz.d1xf.cn/v-U6103652UK?from=singlemessage&isappinstalled=0'>中体彩招聘信息</a>";
            ErrorMessage errorMessage = CustomerService.SendMessage(new ResponseTextMessage(requestMessage.FromUserName, requestMessage.ToUserName, DateTime.Now, string.Format("自动回复客服消息，请求内容如下：\r\n{0}", requestMessage.ToString())));
            if (!errorMessage.IsSuccess)
                Message.Insert(new Message(MessageType.Exception, errorMessage.ToString()));
            return response;
        }
        /// <summary>
        /// 请求记录当前用户的IP信息
        /// </summary>
        /// <returns></returns>
        public ActionResult ReportIpAddress()
        {
            bool flag=IpAddress.Report(Request);
            return Content(flag?"请求成功！":"请求失败！");
        }
    }
}
